/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelefoneDialog.java
 *
 * Created on 21/10/2011, 15:11:24
 */

package br.com.mocamorena.view.dialog;

import br.com.mocamorena.exception.InputValidationException;
import br.com.mocamorena.model.Telefone;
import br.com.mocamorena.model.constant.TipoTelefone;
import br.com.mocamorena.view.ErrorsList;
import br.com.mocamorena.view.StateEntityWindow;
import br.com.mocamorena.view.UserError;
import br.com.mocamorena.view.UtilitiesGUI;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Diego
 */
public class TelefoneDialog extends javax.swing.JDialog {

    private Telefone telefone;
    private final static String titleWindow = "Telefone";
    private StateEntityWindow stateEntity;
    
    public TelefoneDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Telefone telefone) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setTelefone(telefone);
        setLocationRelativeTo(null);
        organizeWindow();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tipoCombo = new javax.swing.JComboBox();
        dddField = new javax.swing.JFormattedTextField();
        numeroField = new javax.swing.JFormattedTextField();
        ramalField = new javax.swing.JFormattedTextField();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        dddErrorLabel = new javax.swing.JLabel();
        numeroErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Tipo:");

        jLabel2.setText("DDD:");

        jLabel3.setText("Número:");

        jLabel4.setText("Ramal:");

        UtilitiesGUI.respondToArrowEnterKey(tipoCombo);
        tipoCombo.setModel(new DefaultComboBoxModel(TipoTelefone.values()));

        UtilitiesGUI.respondToArrowEnterKey(dddField);
        try {
            dddField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        dddField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        try {
            numeroField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        numeroField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        UtilitiesGUI.respondToArrowEnterKey(numeroField);

        try {
            ramalField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        ramalField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        UtilitiesGUI.respondToArrowEnterKey(ramalField);

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        dddErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        numeroErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(26, 26, 26)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel4)
                    .add(jLabel3)
                    .add(jLabel2)
                    .add(jLabel1))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(tipoCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 81, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(dddField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(dddErrorLabel))
                    .add(ramalField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(numeroField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 121, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(numeroErrorLabel)))
                .addContainerGap(133, Short.MAX_VALUE))
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(85, 85, 85)
                .add(confirmarButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(cancelarButton)
                .addContainerGap(74, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(tipoCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(dddField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(dddErrorLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel3)
                            .add(numeroField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(numeroErrorLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(ramalField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(confirmarButton)
                    .add(cancelarButton))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            createTelefone();
            dispose();
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
}//GEN-LAST:event_confirmarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
}//GEN-LAST:event_cancelarButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                TelefoneDialog dialog = new TelefoneDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel dddErrorLabel;
    private javax.swing.JFormattedTextField dddField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel numeroErrorLabel;
    private javax.swing.JFormattedTextField numeroField;
    private javax.swing.JFormattedTextField ramalField;
    private javax.swing.JComboBox tipoCombo;
    // End of variables declaration//GEN-END:variables

    private void setTelefone(Telefone telefone) {
        if (telefone == null) {
            return;
        }
        this.telefone = telefone;
        tipoCombo.setSelectedItem(telefone.getTipo());
        dddField.setText(telefone.getDdd());
        numeroField.setText(telefone.getNumero());
        ramalField.setText(telefone.getRamal());
    }

    private void createTelefone() {
        if (telefone == null) {
            telefone = new Telefone();
        }
        telefone.setTipo((TipoTelefone) tipoCombo.getSelectedItem());
        telefone.setDdd(dddField.getText());
        telefone.setNumero(numeroField.getText());
        telefone.setRamal(ramalField.getText());
    }
    
    public Telefone objetoTelefone() {
        return telefone;
    }

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            tipoCombo.setSelectedItem(TipoTelefone.CELULAR);
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }
    
    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (dddField.getText().equals("  ")) {
            errorsList.addError(new UserError(dddErrorLabel, "O DDD do telefone não foi informado."));
        }
        if (numeroField.getText().equals("    -    ")) {
            errorsList.addError(new UserError(numeroErrorLabel, "O número do telefone não foi informado."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }
    
    private void isShowErrorsLabel(boolean show) {
        dddErrorLabel.setVisible(show);
        numeroErrorLabel.setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
}
